﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Wpf_ClientLourd.BusinessObject;
using Wpf_ClientLourd.ServiceBP;
using System.Collections.ObjectModel;
using System.Data;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO; 

namespace Wpf_ClientLourd
{
    /// <summary>
    /// Logique d'interaction pour ListeBP.xaml
    /// </summary>
    public partial class ListeBP : Window
    {
        User user;
        Parametres param;
        public bool isOK;
        public int numrow;
        List<BPDTO> listeBPDTO;
        ServiceBP.ServiceBPClient clientBP;
        ObservableCollection<BP> collectionBP;

        public ListeBP(User user, Parametres param, List<BPDTO> listeBPDTO)
        {
            InitializeComponent();

            this.user = user;
            this.param = param;
            this.user = user;
            this.param = param;
            this.lbl_nom.Content = "Bonjour " + user.preUser.ToUpper() + " " + user.nomUser.ToUpper();
            this.isOK = true;
            this.numrow = 1;
            this.listeBPDTO = listeBPDTO;

            //Initialisation du client pour le web service
            clientBP = new ServiceBP.ServiceBPClient();

            //On transforme la liste en ObservableCollection pour la mapper au gridview de la page
            collectionBP = new ObservableCollection<BP>();
            
            if (listeBPDTO.LongCount() != 0)
            {
                int cptBP = 0;
                foreach (BPDTO bpdto in listeBPDTO)
                {
                    cptBP++;
                    BP bp = new BP(bpdto);
                    bp.numAff = cptBP;
                    collectionBP.Add(bp);
                    
                }
                DataGridBP.ItemsSource = collectionBP;
                lbl_nbBP.Content = cptBP + " BP générés par le système";
            }

            else
            {
                MessageBox.Show("Aucun BP a éditer", "Attention : Aucun BP", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                isOK = false;
                this.Close();
            }
            
        }

        private void bt_imprimer_Click(object sender, RoutedEventArgs e)
        {
            
            //Génération du fichier pdf
            Document pdfBP = new Document();
            DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0);
            string stDt = dt.ToShortDateString();
            string path = @"C:\Users\Matthieu\Desktop\";
            string filename = path + "ListeBP" + "-" + stDt.Replace("/", "").ToString()+".pdf";
            
            try
            {

                PdfWriter.GetInstance(pdfBP, new FileStream(filename, FileMode.Create, FileAccess.ReadWrite));
                pdfBP.Open();

                //PdfPTable tableG = new PdfPTable(1);

                int cptBP = 0;

                foreach (BP bP in collectionBP)
                {


                    //Création tableau
                    PdfPTable table = new PdfPTable(7);
                    table.WidthPercentage = 100;
                    Font title = new Font(Font.FontFamily.HELVETICA, 20f, Font.BOLD);
                    Chunk titre = new Chunk("BP N°" + bP.id, title);
                    PdfPCell cell = new PdfPCell(new Phrase(titre));
                    cell.Colspan = 7;
                    cell.HorizontalAlignment = 1;
                    table.AddCell(cell);

                    Font bold = new Font(Font.FontFamily.HELVETICA, 12f, Font.BOLD);
                    Chunk cBold0 = new Chunk("");
                    //Chunk cBold1 = new Chunk("BP", bold);
                    Chunk cBold2 = new Chunk("N° BP", bold);
                    Chunk cBold3 = new Chunk("Date BP", bold);
                    Chunk cBold5 = new Chunk("Commande", bold);
                    Chunk cBold6 = new Chunk("Type", bold);
                    PdfPCell cellBP0 = new PdfPCell(new Phrase(cBold0));
                    cellBP0.HorizontalAlignment = 1;
                    //PdfPCell cellBP1 = new PdfPCell(new Phrase(cBold1));
                    //cellBP1.HorizontalAlignment = 1;
                    PdfPCell cellBP2 = new PdfPCell(new Phrase(cBold2));
                    cellBP2.HorizontalAlignment = 1;
                    PdfPCell cellBP3 = new PdfPCell(new Phrase(cBold3));
                    cellBP3.HorizontalAlignment = 1;
                    cellBP3.Colspan = 2;
                    PdfPCell cellBP5 = new PdfPCell(new Phrase(cBold5));
                    cellBP5.HorizontalAlignment = 1;
                    cellBP5.Colspan = 2;
                    PdfPCell cellBP6 = new PdfPCell(new Phrase(cBold6));
                    cellBP6.HorizontalAlignment = 1;
                    table.AddCell(cellBP0);
                    //table.AddCell(cellBP1);
                    table.AddCell(cellBP2);
                    table.AddCell(cellBP3);
                    table.AddCell(cellBP5);
                    table.AddCell(cellBP6);

                    //Génération du code barre BP
                    System.Drawing.Bitmap barecodeBP;
                    iTextSharp.text.Image codeBP = null;
                    Barcode128 code = new Barcode128();
                    code.CodeType = Barcode.CODE128;
                    code.ChecksumText = true;
                    code.GenerateChecksum = true;
                    code.StartStopText = true;
                    code.Code = bP.id.ToString(); ;
                    barecodeBP = new System.Drawing.Bitmap(code.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White));
                    codeBP = iTextSharp.text.Image.GetInstance(barecodeBP, System.Drawing.Imaging.ImageFormat.Png);

                    //On remplit la ligne du BP
                    table.AddCell(codeBP);
                    //table.AddCell((cptBP + 1).ToString());
                    table.AddCell(bP.id.ToString());
                    PdfPCell cellDt = new PdfPCell(new Phrase(bP.date.ToShortDateString()));
                    cellDt.Colspan = 2;
                    table.AddCell(cellDt);
                    PdfPCell cellCmd = new PdfPCell(new Phrase(bP.id_cmd.ToString()));
                    cellCmd.Colspan = 2;
                    table.AddCell(cellCmd);
                    table.AddCell(bP.type);


                    //Appel du web service pour récupérer les lignes de BP
                    List<LgBpDTO> Listlgbp = clientBP.GetLgBPByBP(bP.id).ToList();

                    if (Listlgbp.Count > 0)
                    {
                        //On génère le header pour les lignes
                        Font bold2 = new Font(Font.FontFamily.HELVETICA, 11f, Font.BOLD);
                        Chunk cBold11 = new Chunk("N°", bold);
                        Chunk cBold12 = new Chunk("Code Barre", bold);
                        Chunk cBold14 = new Chunk("Emplacement", bold);
                        Chunk cBold16 = new Chunk("Ref", bold);
                        Chunk cBold13 = new Chunk("Quantité", bold);
                        Chunk cBold15 = new Chunk("Unité", bold);

                        PdfPCell cellBP11 = new PdfPCell(new Phrase(cBold11));
                        cellBP11.HorizontalAlignment = 1;
                        PdfPCell cellBP12 = new PdfPCell(new Phrase(cBold12));
                        cellBP12.HorizontalAlignment = 1;
                        PdfPCell cellBP14 = new PdfPCell(new Phrase(cBold14));
                        cellBP14.HorizontalAlignment = 1;
                        cellBP14.Colspan = 2;
                        PdfPCell cellBP16 = new PdfPCell(new Phrase(cBold16));
                        cellBP16.HorizontalAlignment = 1;
                        PdfPCell cellBP13 = new PdfPCell(new Phrase(cBold13));
                        cellBP13.HorizontalAlignment = 1;
                        PdfPCell cellBP15 = new PdfPCell(new Phrase(cBold15));
                        cellBP15.HorizontalAlignment = 1;

                        table.AddCell(cellBP11);
                        table.AddCell(cellBP12);
                        table.AddCell(cellBP14);
                        table.AddCell(cellBP16);
                        table.AddCell(cellBP13);
                        table.AddCell(cellBP15);


                    }
                    //On remplit les lignes du tableau avec les informations
                    for (int i = 0; i < Listlgbp.Count(); i++)
                    {
                        System.Drawing.Bitmap barecode;
                        iTextSharp.text.Image codeB = null;
                        LgBpDTO lg = Listlgbp.ElementAt(i);

                        //Génération du code barre
                        string prodCode = lg.id.ToString();
                        if (prodCode.Length > 0)
                        {
                            Barcode128 code128 = new Barcode128();
                            code128.CodeType = Barcode.CODE128;
                            code128.ChecksumText = true;
                            code128.GenerateChecksum = true;
                            code128.StartStopText = true;
                            code128.Code = prodCode;
                            barecode = new System.Drawing.Bitmap(code128.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White));
                            codeB = iTextSharp.text.Image.GetInstance(barecode, System.Drawing.Imaging.ImageFormat.Png);

                        }

                        //On appelle le webService pour récuperer les informations sur les emplacements
                        EmplacementDTO emp = clientBP.GetEmplacementByID(lg.idEmplacement);

                        //table.AddCell(cptBP + 1 + "." + lg.numeroLigne.ToString());
                        table.AddCell(lg.id.ToString());
                        table.AddCell(codeB);
                        PdfPCell cellEmp = new PdfPCell(new Phrase(emp.libEmplacement));
                        cellEmp.Colspan = 2;
                        table.AddCell(cellEmp);
                        table.AddCell(lg.refArticle);
                        table.AddCell(lg.qteAPrepa.ToString());

                        switch (lg.codeUnite)
                        {
                            case "PAL": table.AddCell("Palette"); break;
                            case "P": table.AddCell("Pièce"); break;
                        }

                    }


                    //Saut de page
                    pdfBP.Add(table);
                    pdfBP.Add(Chunk.NEXTPAGE);

                    cptBP++;
                }

                //pdfBP.Add(tableG);
                pdfBP.Close();

                ImpressionBP imp = new ImpressionBP(filename);
                imp.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.InnerException.ToString(), "Erreur Génération PDF", MessageBoxButton.OK);
            }

        }

        private void bt_retour_Click(object sender, RoutedEventArgs e)
        {
            MenuAdminBP mnA = new MenuAdminBP(this.user, this.param);
            mnA.Show();
            this.Close();
        }

    }
}
